#include "FlyingAIComponent.h"
#include "GameObject.h"
#include "..\Managers\GameObjectManager.h"
#include "..\Math\ExtraMath.h"
#include "PhysicsComponent.h"

FlyingAIComponent::FlyingAIComponent(const std::string& p_target) : m_target(p_target), m_minDistance(9.0f), m_aiState(AI_FLYING_IDLE)
{
	m_aiFuncPtr[AI_FLYING_IDLE] = &FlyingAIComponent::idle;
	m_aiFuncPtr[AI_FLYING_ATTACKING] = &FlyingAIComponent::attacking;
	m_aiFuncPtr[AI_FLYING_RETURNING] = &FlyingAIComponent::returning;
	
}
FlyingAIComponent::~FlyingAIComponent(void){}

void FlyingAIComponent::init()
{
	m_idleYPos = static_cast<PhysicsComponent*>(getOwner()->getComponent("PhysicsComponent"))->getPosition().y;
}

void FlyingAIComponent::update(const GameTime& p_gameTime)
{
	(this->*m_aiFuncPtr[m_aiState])();
}

void FlyingAIComponent::idle()
{
	GameObject* go = getOwner()->getGameObjectManager()->getGameObject(m_target);
	if (go != nullptr)
	{
		float distance = ExtraMath::distance(go->getPosition().x, getOwner()->getPosition().x);
		if (distance <= m_minDistance)
		{
			m_startPosition = getOwner()->getPosition();
			m_attackPosition = go->getPosition();
			m_attackDirection = m_attackPosition - getOwner()->getPosition();
			m_distance = m_attackDirection.magnitude();
			m_distanceLeft = m_distance;
			m_attackDirection.normalize();
			static_cast<PhysicsComponent*>(getOwner()->getComponent("PhysicsComponent"))->getBody()->SetLinearVelocity(b2Vec2(m_attackDirection.x * 1.5f, m_attackDirection.y * 1.5f));
			m_aiState = AI_FLYING_ATTACKING;
		}
	}
}

void FlyingAIComponent::attacking()
{
	PhysicsComponent* pc = static_cast<PhysicsComponent*>(getOwner()->getComponent("PhysicsComponent"));
	vn::Vector2 pos = m_attackPosition - getOwner()->getPosition();
	m_distance -= pc->getBody()->GetLinearVelocity().LengthSquared();

	if (m_distance <= 9.0f)
	{
		float xpos = m_attackPosition.x - m_startPosition.x;
		m_startPosition = vn::Vector2(m_attackPosition.x + xpos, m_idleYPos);
		m_attackDirection = m_startPosition - getOwner()->getPosition();
		m_distance = m_attackDirection.magnitude();
		m_attackDirection.normalize();
		pc->getBody()->SetLinearVelocity(b2Vec2(m_attackDirection.x * 1.5f, m_attackDirection.y * 1.5f));
		m_aiState = AI_FLYING_RETURNING;
	}
}

void FlyingAIComponent::returning()
{
	PhysicsComponent* pc = static_cast<PhysicsComponent*>(getOwner()->getComponent("PhysicsComponent"));
	vn::Vector2 pos = m_attackPosition - getOwner()->getPosition();
	float test = pc->getBody()->GetLinearVelocity().LengthSquared();
	m_distance -= pc->getBody()->GetLinearVelocity().LengthSquared();
	if (m_distance <= 9.0f)
	{
		float xVel = 0.0f;
		float xDir = pc->getBody()->GetLinearVelocity().x;
		if (xDir >= 0.0f)
			xVel = -1.5f;
		else
			xVel = 1.5f;
		pc->getBody()->SetLinearVelocity(b2Vec2(xVel, 0.0f));
		m_aiState = AI_FLYING_IDLE;
	}
}